#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import logging
logging.basicConfig(level=logging.INFO)
import pdb
import sys
import  shutil 
import  xml.dom.minidom
import tarfile
import datetime


'依照DSV提供的pkg.sh编写python版本，目的是跨平台，易维护'
__author__='fengxw'

global _pkg_name 
_pkg_name = ''
global _pkg_version
_pkg_version = ''
_this_file_path = os.path.split(os.path.realpath(__file__))[0]
logging.info('this py file in this path:'+_this_file_path)

global _mdb_path
_mdb_path = _this_file_path+'/'+'mdb'   # default path is ./mdb
global _idb_path
_idb_path = ''
global _free_key
_free_key=''
global _dsv_ver
_dsv_ver='20181122'
global _dsv_sdk_root_path
_dsv_sdk_root_path='/work/DSV_SDK_'+_dsv_ver
global _strip_type
_strip_type='1'
global _is_make_sampling
_is_make_sampling='0'
global is_copy_to_top_
is_copy_to_top_='0'
global is_package_debug_symbol_
is_package_debug_symbol_ = '0'

def parsexml(xml_path):
	logging.info('prasexml start :'+xml_path)
	dom = xml.dom.minidom.parse(xml_path)
	root = dom.documentElement
	pkg_nodes = root.getElementsByTagName('package')
	pkg_node = pkg_nodes[0]
	global _pkg_name 
	_pkg_name = pkg_node.firstChild.data
	logging.info('pkg_name is:'+_pkg_name)

	pkg_versions = root.getElementsByTagName('version')
	pkg_version = pkg_versions[0]
	global _pkg_version
	_pkg_version = pkg_version.firstChild.data
	logging.info('pkg_version is:'+_pkg_version)
	logging.info('prasexml end ---->')



def buildDirs( beBuildDirs ):
	logging.info('buildDirs start ---->')
	for bDir in beBuildDirs:
		if False == os.path.exists(bDir):
			logging.info('dir :'+bDir+' not exists; build it')
			os.mkdir(bDir)
		else:
			logging.info('dir :'+bDir+' already  exists; not do something')
	logging.info('buildDirs end ---->')

def copyFolder(src , dst):
	if True == os.path.exists(dst):
		logging.info('注意：'+dst+' 文件夹已经存在，现在将要删除它！')
		#choice = raw_input('确定要删除 '+dst+' 吗？y/n ?')
		#if 'y' == choice :
			#logging.info('您选择 y ， 那我就删除 '+dst+'啦！不许反悔呦!')
		shutil.rmtree(dst)
		shutil.copytree(src , dst)
		#else:
			#logging.info('您选择：'+choice +' ,那就不删除 '+dst+'啦！')
			#logging.info('打包过程终止！待您手动删除 '+dst+' 之后，再次运行此脚本！')
			#sys.exit()
	else:
		shutil.copytree(src , dst)


def expandDirs( src , dst ):
	logging.info('expandDirs start ---->')
	copyFolder(src , dst)
	logging.info('expandDirs end ---->')


global _bePkgList
_bePkgList = [[]]

#def excludeDirs( dirs ,strip_type ):
#	logging.info(' exclude dirs from:'+ dirs +','+ strip_type)
#	fileList = []
#	if(True == os.path.exists( dirs+'/navi_origin' )):
#		shutil.move( dirs+'/navi_origin' , dirs+'/../')
#		fileList.append( [dirs+'/../'+'navi_origin' , 'navi_origin'])
#		logging.info(' move '+dirs+' navi_origin  into ' +dirs+'/../')
#	if(True == os.path.exists( dirs+'/navi.dbg' )):
#		shutil.move( dirs+'/navi.dbg' , dirs+'/../')
#		fileList.append( [dirs+'/../'+'navi.dbg' , 'navi.dbg'])
#		logging.info(' move '+dirs+' navi.dbg  into ' +dirs+'/../')
#
#	if(len(fileList) > 0 and  '1'==strip_type):
#		pkg_file_name = dirs +'/../' +'navi_debug.tar.gz'
#		pkg( pkg_file_name ,  fileList)



def pkg(  pkg_final_name , bePkgList):
	logging.info('pkg start, is:'+pkg_final_name)
	pkg_file = tarfile.open(pkg_final_name , 'w:gz')

	for item in bePkgList:
		pkg_file.add(item[0] , item[1])

	pkg_file.close()
	logging.info('pkg end ---->')

def run( build_type  , strip_type, sdk_ver , is_free , is_make_sampling , is_copy_to_top , is_package_debug_symbol):
	global _this_file_path
	global _pkg_name
	global _pkg_version
	global _mdb_path
	global _free_key
	if('1'==is_free):
		_free_key='_free'
	global _dsv_ver
	_dsv_ver = sdk_ver
	global _strip_type
	_strip_type = strip_type
	global _dsv_sdk_root_path
	_dsv_sdk_root_path='/work/DSV_SDK_'+_dsv_ver
	global _is_make_sampling
	_is_make_sampling = is_make_sampling
	global is_copy_to_top_
	is_copy_to_top_ = is_copy_to_top
	global is_package_debug_symbol_
	is_package_debug_symbol_ = is_package_debug_symbol

	logging.info('run start ---->')
	now = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
	pkg_target_path = _this_file_path+ '/' + '../../pkg/' +now

	if(False == os.path.exists(pkg_target_path)):
		os.mkdir(pkg_target_path)

	shutil.copyfile(_this_file_path +'/'+'manifest.xml' ,
			pkg_target_path +'/'+'manifest.xml')

	bePkgList = [
			[pkg_target_path+'/bin' , 'bin'],
			[pkg_target_path+'/lib' , 'lib'],
			[pkg_target_path+'/res' , 'res'],
			[pkg_target_path+'/manifest.xml' , 'manifest.xml']
			]

	beBuildDirs = [
			#pkg_target_path+'/'+'bin' , 删除这一条，因为在之后的copytree时会创建
			pkg_target_path+'/'+'lib', 
			pkg_target_path+'/'+'res']

	parsexml(pkg_target_path+'/'+'manifest.xml')
	buildDirs(beBuildDirs );

	src = pkg_target_path+'/'+ '../../../../../../' + 'Bin/LINUX/ARM_64/' + build_type;
	dst = pkg_target_path+'/'+'bin'
	logging.info(" I want to copy mxnavi from path:"+src)
	logging.info(" copy to path:"+dst)
	expandDirs(src , dst );

	strip_navi(dst , dst+'/../')#srip navi debug symbol

	if('1' == is_package_debug_symbol_):
		package_debug_symbol(dst+'/../')#package debug symbol

	#copy navi debug info to other pkg 
	#excludeDirs( dst ,strip_type);

	#copy mdb to res folder
	#parseMDBPath()
	#mdb_dst = pkg_target_path+'/'+'res'+'/mdb'
	#expandDirs(_mdb_path , mdb_dst)

	#copy idb to res folder
	#idb_dst = pkg_target_path+'/'+'res'+'/idb'
	#expandDirs(_idb_path , idb_dst);
	
	mxversion = parseMXVersion(build_type)

	pkg_final_name =  pkg_target_path+'/'+_pkg_name +'-'+ _pkg_version+'-'+mxversion+ '-' + 'sdkver_' + sdk_ver +_free_key+'.pkg'
	pkg(pkg_final_name , bePkgList)
	logging.info(' 普通版本制作完成 ')

	if('1' == is_copy_to_top_):
		copy_to_top(pkg_final_name)

	if('1'==_is_make_sampling):
		logging.info(' 开始制作采样版本........... ')
		make_sampling_pkg(pkg_target_path , mxversion)
		logging.info(' 采样版本制作完成 ')


	logging.info('run  end ---->')
	logging.info('恭喜您！成功打包！运气真好！')

def extract(beExtractFilePath , place_path):
	logging.info('extract start ')
	try:
		beExtractFile = tarfile.open(beExtractFilePath ,'r:*');
		son_file_names = beExtractFile.getnames();
		for son_file_name in son_file_names:
			beExtractFile.extract(son_file_name ,place_path)
		beExtractFile.close()
	except Exception,e:
		raise Exception,e
	logging.info('extract end ')

def parseMXVersion(build_type ):
	targetFilePath = _this_file_path +'/'+ '../../../../../../' + 'Bin/LINUX/ARM_64/'+build_type+'/mxversion.dat'
	logging.info("prase mxversion.dat from path:"+ targetFilePath)
	if False == os.path.exists(targetFilePath):
		logging.error("targetFile:"+targetFilePath +" not exists; exit script" )
		sys.exit()
	else:
		targetFile = open( targetFilePath , "r" )
		if(targetFile):
			lines = targetFile.readlines()
			version_str =  lines[0].strip('\n')
			version_str =  version_str.strip('\r')
			mxversion = version_str.split(":")[2]
			logging.info("obtain mxversion Success! is :"+mxversion)
			return mxversion
		else:
			logging.error("open file:"+targetFilePath+" Failed! exit script")
			sys.exit()
	pass

#def parseMDBPath():
#	global _mdb_path
#	global _idb_path
#	logging.error(' start parseMDBPath ----------------------------------->')
#	beParseFilePath = _this_file_path+'/'+ project_root_path + '../../' + '../../Bin/LINUX/X86_64/Release/dubheconfig.dat'
#	if False == os.path.exists(beParseFilePath):
#		logging.error('be parsed file:'+beParseFilePath+' not exists; exit script')
#		sys.exit()
#	else:
#		beParaseFile = open( beParseFilePath , "r")
#		logging.info("be parsed file is:"+beParseFilePath)
#		if(beParaseFile):
#			lines = beParaseFile.readlines()
#			#pdb.set_trace()
#			for line in lines:
#				logging.info(line)
#				if(len(line.split(",")) >=2 ):
#					str1 = line.split(",")[0]
#					str2 = line.split(",")[1]
#					if('$DBPATH' == str1):
#						_mdb_path = str2.split("db1")[0]
#						logging.info(" obtain mdb path Success! is:"+_mdb_path)
#					if('$IDBPATH' == str1):
#						_idb_path = str2.strip('\n')
#						_idb_path = _idb_path.strip('\r')
#						logging.info(" obtain idb path Success! is:"+_idb_path)
#		else:
#			logging.error('open file:'+beParseFilePath+' Failed! exit script:')
#			sys.exit()
#	logging.error(' end parseMDBPath ----------------------------------->')
#	pass
#=================test code =================================================

def strip_navi(src_path , dst_path):
	global _dsv_sdk_root_path
	shutil.copyfile(src_path+'/navi' ,dst_path+'/navi')
	tool = _dsv_sdk_root_path +'/sdk/sv-g6s-system-sdk/sysroots/x86_64-oesdk-linux/usr/bin/aarch64-poky-linux/aarch64-poky-linux-objcopy'
	os.system( tool+' --only-keep-debug '+ src_path+'/navi'+' ' + src_path+'/navi.dbg')
	os.system( tool+' --strip-debug '+ src_path+'/navi' )
	shutil.move(src_path+'/navi.dbg' , dst_path)

def package_debug_symbol(src_path):
	logging.info(' package debug symbol in dir:'+src_path)
	fileList = []
	if(True == os.path.exists( src_path+'navi' )):
		fileList.append( [src_path+'navi' , 'navi'])
	if(True == os.path.exists( src_path+'navi.dbg' )):
		fileList.append( [src_path+'navi.dbg' , 'navi.dbg'])

	if(len(fileList) > 0 and  '1'==_strip_type):
		pkg_file_name = src_path +'navi_debug'+_free_key+'.tar.gz'
		pkg( pkg_file_name ,  fileList)
		copy_to_top(pkg_file_name)

def make_sampling_pkg(cur_path , mxversion):
	global _this_file_path
	global _pkg_name
	global _pkg_version
	global _mdb_path
	global _free_key
	global _dsv_ver
	global _strip_type
	global _dsv_sdk_root_path
	global _is_make_sampling
	sampling_path = cur_path + '/sampling'
	if(False == os.path.exists(sampling_path)):
		os.mkdir(sampling_path)

	copyFolder(cur_path+'/bin' ,sampling_path+'/bin') 
	copyFolder(cur_path+'/lib' ,sampling_path+'/lib') 
	copyFolder(cur_path+'/res' ,sampling_path+'/res') 
	shutil.copyfile(cur_path+'/manifest.xml' , sampling_path+'/manifest.xml')

	sampling_cfg_path = _this_file_path+'/../../../../config/sampling_cfg'
	#pdb.set_trace()
	for root , dirs , files in  os.walk(sampling_cfg_path , topdown=False):
		for file_item in files:
			logging.info('根据配置文件：'+file_item+' 生成采样版本')
			file_item_key = file_item.split('.')[0]
			file_item_type = file_item.split('.')[1]
			if('json' == file_item_type):
				if(True == os.path.exists(sampling_path+'/bin'+'/tsconfig.json')):
					os.remove(sampling_path+'/bin'+'/tsconfig.json')
				shutil.copyfile(os.path.join(root ,file_item) , sampling_path+'/bin'+'/tsconfig.json')
				bePkgList = [
					[sampling_path+'/bin' , 'bin'],
					[sampling_path+'/lib' , 'lib'],
					[sampling_path+'/res' , 'res'],
					[sampling_path+'/manifest.xml' , 'manifest.xml']
					]
				#pdb.set_trace()
				pkg_final_name =  sampling_path+'/'+_pkg_name +'-'+ _pkg_version+'-'+mxversion+ '-' + 'sdkver_' + _dsv_ver +'_'+file_item_key+_free_key+'.pkg'
				pkg(pkg_final_name , bePkgList)
				copy_to_top(pkg_final_name)
			else:
				logging.info('不处理扩展名为非json的文件')

def copy_to_top(becopy_file):
	global _this_file_path
	top_path = _this_file_path+'/../../../../../../'+'suy/'
	#pdb.set_trace()
	if(False == os.path.exists(top_path)):
		os.mkdir(top_path)

	top_path += 'LINUX/'
	if(False == os.path.exists(top_path)):
		os.mkdir(top_path)
	logging.info('copy file:'+becopy_file+' to top:'+top_path)
	shutil.copy(becopy_file , top_path)


if __name__=='__main__':
	logging.info('argv is:')
	logging.info(sys.argv)
	for i in range(len(sys.argv)):
		if sys.argv[i] == '-parse':
			parsexml(sys.argv[i+1])
		elif sys.argv[i] == '-build':
			buildDirs()
		elif sys.argv[i] == '-expand':
			expandDirs()
		elif sys.argv[i] == '-pkg':
			pkg()
		elif sys.argv[i] == '-run':
			run( sys.argv[i+1] , sys.argv[i+2], sys.argv[i+3], sys.argv[i+4] , sys.argv[i+5] , sys.argv[i+6] , sys.argv[i+7] )
		elif sys.argv[i] == '-extract':
			extract(sys.argv[i+1] , sys.argv[i+2])
		elif sys.argv[i] == '-pm':
			parseMXVersion(sys.argv[i+1])
		elif sys.argv[i] == '-mdb':
			parseMDBPath()
		elif sys.argv[i] == '-sampling':#编译采样版本
			sampling_pkg(sys.argv[i+1] , sys.argv[i+2])

